package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext orderContext = (CreateOrderContext) context;
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        List<Long> buyProductIds = orderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {

            buyProductIds = cartProductDtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());

        }
        buyProductIds.sort(Long::compareTo);

        List<Stock> stockList = null;


        stockList = stockMapper.findStocksForUpdate(buyProductIds);

        if (CollectionUtils.isEmpty(stockList)) {
            System.out.println("stockMapper异常捕获：SQL异常！数据库异常！");

            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        if (stockList.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        for (CartProductDto cartProductDto : cartProductDtoList) {

            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            // 超买了
            Stock st = null;


            st = stockMapper.selectStock(productId);
            if (stock == null) {
                System.out.println("stockMapper异常捕获：SQL异常！数据库异常！");
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
            }
            if (productNum > st.getRestrictCount()) {
                throw new BizException(OrderRetCode.ITEM_COUNT_LIMIT.getCode(), "商品仅限购买" + st.getRestrictCount() + "个");
            }

            stockMapper.updateStock(stock);
            if (stock == null) {
                System.out.println("stockMapper异常捕获：SQL异常！数据库异常！");
            }
        }
        return true;
    }
}